<template>
  <edit-dialog :centerDialogVisible="visible" :tilte="info && info.memberId ? '编辑人员' : '新增人员'" @Cancel="handleCancel"
    @Submit="handleSubmit(memberFormRef)" :width="dialogWidth">
    <template #content>
      <div>
        <el-form ref="memberFormRef" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="姓名" prop="memberName">
            <el-input v-model="form.memberName" maxlength="32" />
          </el-form-item>
          <el-form-item label="联系电话" prop="memberPhone">
            <el-input v-model="form.memberPhone" />
          </el-form-item>
          <el-form-item label="所属单位" prop="companyId">
            <el-cascader v-model="form.companyId" :options="companyData" placeholder="请选择所属单位" :show-all-levels="false"
              style="width: 100%" />
          </el-form-item>
          <el-form-item label="角色" prop="memberRole">
            <el-select v-model="form.memberRole" placeholder="请选择角色" style="width: 100%" multiple>
              <el-option v-for="item in roleData" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" :rows="5" type="textarea" maxlength="300" />
          </el-form-item>
        </el-form>
      </div>
    </template>
  </edit-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, defineProps, watch, nextTick, toRaw, computed } from 'vue'
import { useStore } from 'vuex'
import type { FormInstance, FormRules } from 'element-plus'
import { addMember, updateMember } from '@/api/rep/member'
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage } from 'element-plus'

interface RuleForm {
  memberName: string,
  memberPhone?: string,
  companyId?: Array<string> | string,
  memberRole?: Array<string> | string,
  remarks?: string,
  memberId?: string,
  creator?: any
  lastMender?: any
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Object,
    default: () => null,
  },
  // 维修单位
  companyData: {
    type: Object,
    default: () => [],
  },
  // 角色
  roleData: {
    type: Object,
    default: () => [],
  },
  // 用户信息
  userInfo: {
    type: Object,
    default: () => { },
  },
})

const emit = defineEmits(['cancel', 'ok'])

const store = useStore()
// 弹窗标题
const dialogWidth = ref('460px')
const memberFormRef = ref<FormInstance>()
const form = reactive<RuleForm>({
  memberName: '',
  memberPhone: '',
  companyId: [],
  memberRole: [],
  remarks: '',
})

const validatorPhone = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error('请输入联系电话！'))
  if (value && !/^1[3|4|5|7|8|9][0-9]\d{8}$/.test(value)) return callback(new Error('电话号码格式不正确！'))
  callback()
}


const rules = reactive<FormRules>({
  memberName: [{ required: true, message: '请输入姓名', trigger: 'change' }],
  memberPhone: [{ required: true, validator: validatorPhone, message: '电话号码格式不正确！', trigger: 'change' }],
  companyId: [{ required: true, message: '请选择所属单位', trigger: 'change' }],
  memberRole: [{ required: true, message: '请选择角色', trigger: 'change' }],
  // remarks: [{ message: '请输入备注', trigger: 'blur' }],
})

const getParentsById = (list: any[], id: string) => {
  for (let i in list) {
    if (list[i].value == id) {
      //查询到就返回该数组对象的value
      return [list[i].value]
    }
    if (list[i].children) {
      let node: any = getParentsById(list[i].children, id)
      if (node !== undefined) {
        //查询到把父节把父节点加到数组前面
        node.unshift(list[i].value)
        return node
      }
    }
  }
}


const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let fetch = addMember;
      const payload: RuleForm = { ...form };
      if (payload.memberRole && Array.isArray(payload.memberRole)) {
        payload.memberRole = payload.memberRole.join(',')
      }
      if (payload.companyId && Array.isArray(payload.companyId)) {
        payload.companyId = payload.companyId[payload.companyId.length - 1]
      }
      // 编辑
      if (props.info?.memberId) {
        fetch = updateMember;
        payload.memberId = props.info.memberId;
        payload.lastMender = props.userInfo
        // 新增
      } else {
        payload.creator = props.userInfo
      }
      let title = props.info?.memberId ? '修改' : '新增';
      fetch(payload).then((res: any) => {
        if (res?.code === '1') {
          emit('ok')
          ElMessage.success(`${title}成功`)
        } else {
          ElMessage.error(res?.message || `${title}失败，请重试！`);
        }
      }).catch((res) => {
        ElMessage.error(res?.message || `${title}失败，请重试！`)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleCancel = () => {
  emit('cancel')
}


watch(() => props.visible, (val, oldVal) => {
  if (val && val !== oldVal) {
    nextTick(() => {
      if (props.info) {
        const info = toRaw(props.info);
        let arr: any[] = props.companyData;
        form.memberName = info?.memberName || '';
        form.memberPhone = info?.memberPhone || '';
        form.companyId = info?.companyId && getParentsById(arr, info?.companyId) || [];
        form.memberRole = info?.memberRole && info?.memberRole.split(',') || [];
        form.remarks = info?.remarks || '';
      } else {
        form.memberName = '';
        form.memberPhone = '';
        form.companyId = [];
        form.memberRole = [];
        form.remarks = '';
      }
    })
  }
})
</script>